import { defineStore } from 'pinia';

import type { RouteRecordRaw } from 'vue-router';

import { asyncRoutes, constantRoutes, catchAllRoutes } from '@/router';
import { intersection } from '@/utils/index';

/**
 * 获取用户有权限的路由
 * @param routes
 * @param menus
 */
export function filterAsyncRoutes(routes: RouteRecordRaw[], authCodes: Array<any>): RouteRecordRaw[] {
  const result: Array<RouteRecordRaw> = [];

  routes.forEach((route: RouteRecordRaw) => {
    const routeAuthCodes: string[] | any = route?.meta?.authCodes || [];
    const matchedCodes = intersection(authCodes, routeAuthCodes);
    if (matchedCodes.length > 0) {
      if (route.children) {
        route.children = filterAsyncRoutes(route.children, authCodes);
      }
      result.push(route);
    }
  });

  return result;
}

/**
 * @description: 更新路由的redirect指向
 * @param {RouteRecordRaw} routes
 */
export function updateRedirect(routes: RouteRecordRaw[]) {
  routes.forEach((route) => {
    if (route.children && route.children.length > 0) {
      route.redirect = route.children[0].path;
      updateRedirect(route.children);
    }
  });
}

type State = {
  permissionRoutes: RouteRecordRaw[],
  accessedRoutes: RouteRecordRaw[]
}

export const usePermissionStore = defineStore('_permission', {
  state: (): State => ({
    permissionRoutes: [], // 最终要展示到菜单的路由列表
    accessedRoutes: [], // 匹配权限的菜单列表
  }),
  actions: {
    generateRoutes(authCodes: Array<RouteRecordRaw>): Promise<TypeObject> {
      return new Promise((resolve) => {
        const accessedRoutes = filterAsyncRoutes(asyncRoutes, authCodes);
        this.accessedRoutes = accessedRoutes;

        this.permissionRoutes = [...constantRoutes, ...accessedRoutes, ...catchAllRoutes];
        updateRedirect(this.permissionRoutes);

        resolve({
          accessedRoutes,
          permissionRoutes: this.permissionRoutes,
        });
      });
    },
  },
});
